
import shelve
import os

def swrite(key, data, db):
    ''' write to shelve database
    '''
    shdb = shelve.open(db)
    shdb[key] = data
    shdb.close()

def sread(key, db):
    shdb = shelve.open(db)
    data = shdb[key]
    shdb.close()
    return data

def sdelete(key, db):
    shdb = shelve.open(db)
    del shdb[key]
    shdb.close()

def slist(db):
    shdb = shelve.open(db)
    keys = sorted(shdb.keys())
    shdb.close()
    return keys

# exceptions wrapper
def sh_set(key, data, db='sh.db'):
    ''' '''
    try:
        swrite(key, data, db)
        return True
    except:
        return False

def sh_get(key, db='sh.db'):
    ''' '''
    try:
        return sread(key, db)
    except:
        return False
    
def sh_list(db='sh.db'):
    ''' '''
    try:
        return slist(db)
    except:
        return False

def sh_drop(key, db='sh.db'):
    ''' '''
    try:
        sdelete(key, db)
        return True
    except:
        return False

def shlvDb(key, data='', db='sdb.sdb'):
    """
    search whether dhlv.db exists:
        yes - read data using key
        no  - store key and data

    import pepe.p_dm.sdb as s
    par = ['*.dat', '\t', 'n']
    # write to db
    #s.shlvDb('jpk.par', par)
    # read from db
    print s.shlvDb('jpk.par')
    """
    # read value for given key - db exists
    if os.path.exists(db) and data == '':
        if key in slist(db) and data == '':
            return  sread(key, db)
        else:
            return 'n/a'
    # replace value for given key - db exists
    if os.path.exists(db) and data <> '':
        swrite(key, data, db)
        return 1
    # no db no data
    if not os.path.exists(db) and data == '':
        return 'n/a'
    # write for first time - db not exists
    if not os.path.exists(db) and data <> '':
        swrite(key, data, db)
        return 0

if __name__ == "__main__":
    """ """
    pass